# -*- coding: utf-8 -*-

from server.models import db

'''
数据库结构
    { "_id" : , 
    "username" : "", 
    "password" : "", 
    "nickname" : "", 
    "sex" : ""(1男2女), 
    "email" : "", 
    "createDate" : "", 
    "remarks" : "", 
    "role" : ""(1超级管理员2数据管理员3操作员) }
'''


class userDao(object):

    # 初始化变量
    def __init__(self):
        self._collection = db.userTable
        admin = self._collection.find_one({"username": "admin"})
        if admin is None:
            self._collection.insert_one({"username": "admin", "password": "123456"})

    # 账号密码登录 登录成功返回user，失败返回None
    def login(self, username, password):
        user = self._collection.find_one({"username": username, "password": password},
                                         {"username": 1, "nickname": 1, "role": 1})
        return user

    # 查找用户信息
    def select_info(self, user):
        if not isinstance(user, dict):
            return None

        userInfo = self._collection.find_one({"username": user["username"]}, {"_id": 0, "password": 0})
        if userInfo is None:
            return None

        return userInfo

    # 修改用户信息
    def update_info(self, user, info):
        if not isinstance(user, dict):
            return None
        if not isinstance(info, dict):
            return None

        updateInfo = self._collection.find_one({"username": user["username"]})
        if updateInfo is None:
            return None

        for key in info:
            updateInfo[key] = info[key]

        self._collection.update_one({"username": user["username"]}, {'$set': updateInfo})

        userSession = {"username": updateInfo['username'],
                       "nickname": updateInfo['nickname'],
                       "role": updateInfo['role']}

        return userSession

    # 修改用户密码
    def update_password(self, user, oldPassword, newPassword):
        if not isinstance(user, dict):
            return False
        if not isinstance(user, dict):
            return False

        updateInfo = self._collection.find_one({"username": user["username"]})
        if updateInfo is None:
            return False

        if updateInfo['password'] != oldPassword:
            return False
        updateInfo['password'] = newPassword

        self._collection.update_one({"username": user["username"]}, {'$set': updateInfo})

        return True

    # 查询所有的用户
    def select_users(self, user, condition, limit):
        if not isinstance(user, dict):
            return None

        if user['role'] != '1':
            return None

        count = self._collection.find(condition).count()
        if count == 0:
            return count, []

        users = [userInfo for userInfo in self._collection.find(condition, {"_id": 0, "password": 0})]

        return count, users[(limit['page']-1)*limit['limit']:
                            (limit['page']-1)*limit['limit']+limit['limit']]

    # 增加用户
    def add_user(self, user, addUser):
        if not isinstance(user, dict):
            return False
        if not isinstance(addUser, dict):
            return False

        if user['role'] != '1':
            return False

        info = self._collection.find_one({"username": addUser["username"]})
        if info is not None:
            return False

        self._collection.insert_one(addUser)
        return True

    # 删除用户
    def delete_user(self, user, delUser):
        if not isinstance(user, dict):
            return False
        if not isinstance(delUser, dict):
            return False

        if user['role'] != '1':
            return False

        if delUser['username'] == 'admin':
            return False

        info = self._collection.find_one(delUser)
        if info is None:
            return False

        self._collection.delete_one(delUser)
        return True

    # 管理员重置用户密码
    def reset_user_password(self, user, resetUser):
        if not isinstance(user, dict):
            return False

        if user['role'] != '1':
            return False

        if resetUser == 'admin':
            return False

        info = self._collection.find_one({"username": resetUser})
        if info is None:
            return False

        info['password'] = '123456'
        self._collection.update_one({"username": resetUser}, {'$set': info})

        return True


